#pragma once
#include <iostream>
#include <pthread.h>
#include "MyMutex.hpp"

namespace MyCondValArea
{
    using namespace MyMutexArea;
    class MyCondVal
    {
    public:
        MyCondVal()
        {
            int n = ::pthread_cond_init(&_cond, nullptr);
            if (n != 0)
            {
                std::cerr << "pthread_cond_init error" << std::endl;
                exit(1);
            }
        }

        void Wait(MyMutex &mutex) // 等待,释放锁
        {
            int n = ::pthread_cond_wait(&_cond, mutex.GetMutex());
            if (n != 0)
            {
                std::cerr << "pthread_cond_wait error" << std::endl;
                exit(-1);
            }
        }

        void PthreadSignal() // 唤醒
        {
            int n = ::pthread_cond_signal(&_cond);
            if (n != 0)
            {
                std::cerr << "pthread_cond_siganl error" << std::endl;
                exit(-1);
            }
        }
        
        void Notify()
        {
            int n = ::pthread_cond_broadcast(&_cond);
            (void)n;
        }

        ~MyCondVal()
        {
            int n = ::pthread_cond_destroy(&_cond);
            if (n != 0)
            {
                std::cerr << "pthread_cond_destroy error" << std::endl;
                exit(1);
            }
        }

    private:
        pthread_cond_t _cond; // 条件变量
    };
}